package com.alibaba.algo.components.oss;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 阿里云OSS工具类
 * @author: malin
 * @date: 2020-11-3 14:21:03
 */
@Slf4j
@Component
public class AliOssComponent {
	@Value("${ali.oss.endpoint}")
	private String endpoint;
	@Value("${ali.oss.accessKeyId}")
	private String accessKeyId;
	@Value("${ali.oss.accessKeySecret}")
	private String accessKeySecret;
	@Value("${ali.oss.bucketName}")
	private String bucketName;
	@Value("${ali.oss.bucketUrl}")
	private String bucketUrl;

	private OSS getOSSClient() {
		return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
	}

	/**
	 * @Description: 文件上传
	 * @param: inputStream 文件流
	 * @param: fileSuffix  文件后缀名
	 * @author: malin
	 * @date: 2020-11-3 14:50:29
	 */
	public String uploadOss(InputStream inputStream, String fileSuffix) {
		OSS ossClient = getOSSClient();
		String key = getFileName(fileSuffix);
		log.info("key:{}", key);
		PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, inputStream);
		log.info("putObjectResult:{}", JSON.toJSONString(putObjectResult));
		// 关闭OSSClient。
		ossClient.shutdown();
		if (putObjectResult != null) {
			return "https://" + bucketUrl + "/" + key;
		}
		return null;
	}

	/**
	 * @Description: 文件上传
	 * @param: content 文本内容
	 * @author: malin
	 * @date: 2020-11-3 14:50:29
	 */
	public String uploadOss(String content, String fileSuffix) {
		OSS ossClient = getOSSClient();
		String key = getFileName(fileSuffix);
		log.info("key:{}", key);
		PutObjectResult putObjectResult = ossClient.putObject(bucketName, key,
				new ByteArrayInputStream(content.getBytes()));
		log.info("putObjectResult:{}", JSON.toJSONString(putObjectResult));
		// 关闭OSSClient。
		ossClient.shutdown();
		if (putObjectResult != null) {
			return "https://" + bucketUrl + "/" + key;
		}
		return null;
	}

	/**
	 * @Description: 文件上传
	 * @param: localPath 本地文件全路径
	 * @author: xcf
	 * @date: 2020-11-6 14:50:29
	 */
	public String uploadOss(String localPath) {
		File file = new File(localPath);
		if (file.exists() && file.isFile()) {
			OSS ossClient = getOSSClient();
			String fileName = file.getName();
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			String key = getFileName(suffix);
			log.info("key:{}", key);
			PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, file);
			log.info("putObjectResult:{}", JSON.toJSONString(putObjectResult));
			// 关闭OSSClient。
			ossClient.shutdown();
			if (putObjectResult != null) {
				return "https://" + bucketUrl + "/" + key;
			}
		}
		return null;
	}

	/**
	 * @Description: 文件下载
	 * @param remoteFilePath 远程文件url地址
	 * @param localFilePath  本地存放路径
	 * @author: xcf
	 * @date: 2020-11-6 14:50:29
	 */
	public void downloadFile(String remoteFilePath, String localFilePath) {
		URL urlfile = null;
		HttpURLConnection httpUrl = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		File f = new File(localFilePath);
		try {
			urlfile = new URL(remoteFilePath);
			httpUrl = (HttpURLConnection) urlfile.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());
			bos = new BufferedOutputStream(new FileOutputStream(f));
			int len = 2048;
			byte[] b = new byte[len];
			while ((len = bis.read(b)) != -1) {
				bos.write(b, 0, len);
			}
			log.info("文件下载成功");
			bos.flush();
			bis.close();
			httpUrl.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bis.close();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private String getFileName(String fileSuffix) {
		String fileName = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/";
		fileName = fileName + UUID.randomUUID().toString().replace("-", "");
		return fileName + "." + fileSuffix;
	}
}
